//
// Created by root on 10/7/15.
//

#include <string.h>
#include <stdio.h>
#include "request.h"
#include "my_functon.h"

static uthash* _parse_header(char * str){

    uthash * header = NULL,*newHeader;

    char * cpyStr = my_strdup(str),**p=NULL;
    UT_array *headerArr = strsplit(cpyStr,HEAD_CRLF),*tempArr;

    while ( (p=(char**)utarray_next(headerArr,p)) ){

        newHeader = (uthash*)malloc(sizeof(uthash));

        tempArr = strsplit(*p,":");
        if(utarray_len(tempArr) > 1){
            newHeader->name = my_strdup(*((char**)utarray_eltptr(tempArr,0)));
            newHeader->name=strtolow(trim(newHeader->name));
            newHeader->value = my_strdup(*((char**)utarray_eltptr(tempArr,1)));
            newHeader->value=trim(newHeader->value);
        }else{
            newHeader->name = my_strdup(HEAD_METHOD_LINE);
            newHeader->value = my_strdup(*((char**)utarray_eltptr(tempArr,0)));
            newHeader->value=trim(newHeader->value);
        }

        HASH_ADD_STR(header,name,newHeader);
    }

    utarray_free(headerArr);
    free(cpyStr);

    return  header;
}

static void _parse_method_line(request * req){
    uthash * methodLine = NULL;
    HASH_FIND_STR(req->header,HEAD_METHOD_LINE,methodLine);
    if(!methodLine){
        return;
    }
    if(req->method != NULL){
        return;
    }

    char * methdLineStr = my_strdup(methodLine->value);
    UT_array *methodLineArr = strsplit(methdLineStr," ");
    free(methdLineStr);

    req->method = my_strdup(*(char**)utarray_eltptr(methodLineArr,0));
    strtoupper(trim(req->method));
    req->url = my_strdup(*(char**)utarray_eltptr(methodLineArr,1));

    utarray_free(methodLineArr);
}

request * request_init(char *s){
    request * req = (request*)malloc(sizeof(request));
    req->url = NULL;
    req->parameters = NULL;
    req->method = NULL;

    req->str = my_strdup(s);

    req->header = _parse_header(req->str);

    _parse_method_line(req);
    return req;
}

char * get_request_header(request*req,char*name){
    uthash * header = NULL;
    HASH_FIND_STR(req->header,name,header);
    return header ? header->value : NULL;
}

char * get_request_parameters(request*req,char*name){
    uthash * parameter = NULL;
    HASH_FIND_STR(req->parameters,name,parameter);
    return parameter ? parameter->value : NULL;
}

//todo
void request_free(request *req){

}